package com.yystudy.system.service.impl;

import com.yystudy.model.system.SysUser;
import com.yystudy.system.custom.CustomUser;
import com.yystudy.system.service.SysMenuService;
import com.yystudy.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //根据用户名查询数据库，返回该行数据
        SysUser sysUser = sysUserService.getByUsername(s);

        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }

        if (sysUser.getStatus() == 0) {
            throw new RuntimeException("该用户已被禁用");
        }

        //根据用户id查询该用户拥有的权限数据
        List<String> userPermsList = sysMenuService.getUserButtonList(sysUser.getId());

        //转换为Security要求的格式数据
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String perms : userPermsList) {
            //将数据加入集合当中
            authorities.add(new SimpleGrantedAuthority(perms.trim()));
        }
        return new CustomUser(sysUser, authorities);
    }

}
